package com.chen.app.config;

import com.chen.app.pors.SecurityProperties;
import com.chen.app.security.LoginType;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Component(value = "securityAuthenticationSuccessHandler")
public class SecurityAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private SecurityProperties securityProperties;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
        log.info("登陆成功");

        if (LoginType.JSON.equals(securityProperties.getBrowser().getLoginType())){
            //设置返回内容的数据形式和编码格式
            response.setContentType("application/json;charset=UTF-8");
            //将户认证成功的信息以json数据的形式返回给前端
            response.getWriter().write(objectMapper.writeValueAsString(authentication));
        } else {
            //如果登陆成功后不想返回json,可以按照spring-security默认方式进行处理(登录成功后会跳转到引发登录的请求上)
            super.onAuthenticationSuccess(request,response,authentication);
        }
    }
}
